#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <unistd.h>

int main(int argc, char** argv)
{
	int port = 0;	// listening port
	int sockfd = 0;	// listener socket
	int commfd = 0;	// client-server communication socket
	struct sockaddr_in server_addr, cli_addr; // server and cliendt address
	socklen_t srvlen, clilen;	// server and client address lengths
	char buffer[256];	// communication buffer
	int n = 0;			// read and written bytes
	int option = 0;		// socket option

	printf("Server is running...\n");

	// Make sure that port number is provided as a parameter
	if(argc != 2)
	{
		printf("Port number not provided!\n");
		exit(-1);
	}

	// Parse port number from 2nd command line argument
	port = atoi(argv[1]);
	if(port == 0)
	{
		printf("Given port is not a number! (%s)\n", argv[1]);
		exit(-1);
	}
	
	printf("Port number: %d\n", port);

	// Create a TCP socket
	sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(sockfd < 0)
	{
		printf("Error opening socket\n");
		exit(-1);
	}

	// Enable address reuse
	option = 1;
	n = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option));

	// Set up server address properly ("man 7 ip")
	bzero((char*)&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);	// in network byte order
	server_addr.sin_addr.s_addr = INADDR_ANY; // from any interface

	srvlen = sizeof(server_addr);
	// Bind the socket to the given port
	if(bind(sockfd, (struct sockaddr*)&server_addr, srvlen) < 0)
	{
		printf("Error binding socket!\n");
		exit(1);
	}

	// Listen on the socket
	listen(sockfd, 5);	// max 5 clients in the queue

	clilen = sizeof(cli_addr);
	// Accept connections, e.g. via telnet
	// Blocking call
	commfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
	if(commfd < 0)
	{
		printf("Error on accept\n");
		exit(-1);
	}

	// Read from client
	bzero(buffer, 256);	// zero out the buffer
	n = read(commfd, buffer, 255);
	if(n < 0)
	{
		printf("Error reading from socket\n");
		exit(-1);
	}

	printf("Server got this message: %s", buffer);

	// Send back an acknowledgement
	char msg[] = "Acknowledged!\n";
	n = write(commfd, msg, strlen(msg));
	if(n < 0)
	{
		printf("Error writing to socket\n");
		exit(-1);
	}

	printf("Server is done.\n");
	return 0;
}
